//
//  DBManager.m
//
//  Created by 周成龙
//

#import "DBManager.h"

#import "SQLiteTool.h"
#import "MainModel.h"

extern NSString *const kTableName;

@implementation DBManager
DBManager *_manager;

+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[DBManager alloc] init];
    });
    return _manager;
}

- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (void)clearTable {
    NSString *sql = [NSString stringWithFormat:@"drop table '%@';", kTableName];
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        [[SQLiteTool shareSQLiteTool] execSql:sql];
    }
}

/**
 存储
 */
- (void)saveObject:(MainModel *)model {
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model.img_url];
        NSString *sql = [NSString stringWithFormat:@"insert into %@ (sid, uid, unique, content, img_url, create_time, update_time, alert_time, status) values (%@, %@, %@, %@, %@, %@, %@, %@, %@);", kTableName, model.sid, model.uid, model.unique, model.content, data, model.create_time, model.update_time, model.alert_time, model.status];
        [[SQLiteTool shareSQLiteTool] execSql:sql];
    }
}
/**
 通过 id 获取存储数据
 */
- (MainModel *)getObjectById:(NSString *)objectId {
    return nil;
}
/**
 查询数据库所有数据
 */
- (NSArray *)getAllItemsFromTable {
    
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        NSMutableArray *datas = @[].mutableCopy;
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM '%@';", kTableName];
        NSArray *array = [[SQLiteTool shareSQLiteTool] qureySqlite:sql];
        
        for (NSDictionary *dict in array) {
            MainModel *model = [[MainModel alloc] init];
            model.sid = dict[@"sid"];
            model.alert_time = dict[@"alert_time"];
            
            [datas addObject:model];
        }
        return [datas copy];
    }
    return nil;
}
/**
 根据id删数据
 */
- (void)deleteObjectById:(NSString *)objectId {
    if ([[SQLiteTool shareSQLiteTool] openDB]) {
        NSString *sql = [NSString stringWithFormat:@"delete from %@ where sid='%@';", kTableName, objectId];
        [[SQLiteTool shareSQLiteTool] execSql:sql];
    }
}

//- (void)updateObjectById:(MainModel *)model {
//    if ([[SQLiteTool shareSQLiteTool] openDB]) {
//        NSString *sql = [NSString stringWithFormat:@"update %@ set name='%@', time='%@, alert_time='%@', sid='%@';", kTableName, model.name, model.time, model.alert_time, model.sid];
//        [[SQLiteTool shareSQLiteTool] execSql:sql];
//    }
//}

@end
